package top.market.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import org.redisson.MapWriterTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import top.market.model.dto.AddressDTO;
import top.market.model.entity.AddressBook;
import top.market.model.entity.User;
import top.market.model.vo.Result;
import top.market.service.IAddressBookService;
import top.market.util.CurrentUserUtil;

import java.util.List;

/**
 * <p>
 * 地址簿 前端控制器
 * </p>
 *
 * @author li yuhai
 * @since 2025-03-26
 */
@RestController
@RequestMapping("/address")
public class AddressBookController {

    private static final Logger log = LoggerFactory.getLogger(AddressBookController.class);

    @Autowired
    private IAddressBookService addressBookService;

    // 获取详细信息
    @GetMapping("/{id}")
    public Result detail(@PathVariable Integer id) {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        wrapper.eq(AddressBook::getId, id);
        AddressBook one = addressBookService.getOne(wrapper);
        return Result.ok("", one);
    }

    // 用户删除地址by id
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        wrapper.eq(AddressBook::getId, id);
        boolean remove = addressBookService.remove(wrapper);
        if (remove) return Result.ok("删除成功");
        else return Result.error("删除失败");
    }

    // 更新
    @PutMapping("/update")
    public Result updateById(@RequestBody AddressDTO addressDTO) {
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(addressDTO, addressBook);
        if (addressBook.getId() == null || addressBook.getId() == 0) {
            return Result.error("数据有误");
        }
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getId, addressBook.getId());
        wrapper.eq(AddressBook::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        boolean update = addressBookService.update(addressBook, wrapper);
        if (update) return Result.ok("更新成功");
        return Result.error("删除失败");
    }

    @GetMapping("/list")
    public Result list() {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        List<AddressBook> list = addressBookService.list(wrapper);
        return Result.ok("", list);
    }

    @PostMapping("/save")
    public Result save(@RequestBody AddressDTO addressDTO) {
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(addressDTO, addressBook);
        if (StrUtil.isBlank(addressBook.getConsignee()) || StrUtil.isBlank(addressBook.getPhone())
                || StrUtil.isBlank(addressBook.getDetail())) {
            return Result.error("数据没有填写完整");
        }
        Long user_id = CurrentUserUtil.getCustomUserDetails().getId();
        addressBook.setUserId(user_id);
        if (addressBook.getIsDefault() != null && addressBook.getIsDefault().equals(1)) {
            LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(AddressBook::getIsDefault, 0).eq(AddressBook::getUserId, user_id);
            addressBookService.update(wrapper);
        }
        addressBookService.save(addressBook);
        return Result.ok("插入成功");
    }

    // 获取该用户的默认收货地址
    @GetMapping("/default")
    public Result defaultAddress() {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        wrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook one = addressBookService.getOne(wrapper);
        return Result.ok("", one);
    }

    // 更改默认地址
    @PutMapping("/default")
    public Result upDatedefaultAddress(@RequestBody AddressDTO addressDTO) {
        // 先把其他的变为0
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(AddressBook::getIsDefault, 0).eq(AddressBook::getUserId, CurrentUserUtil.getCustomUserDetails().getId());
        addressBookService.update(wrapper);
        // 把这个变为1
        LambdaUpdateWrapper<AddressBook> wrapper1 = new LambdaUpdateWrapper<>();
        wrapper1.set(AddressBook::getIsDefault, 1).eq(AddressBook::getUserId, CurrentUserUtil.getCustomUserDetails().getId())
                        .eq(AddressBook::getId, addressDTO.getId());
        addressBookService.update(wrapper1);
        return Result.ok("修改成功");
    }
}
